#include "tbuttondelegate.h"

TButtonDelegate::TButtonDelegate(QSqlRelationalDelegate *parent):QSqlRelationalDelegate(parent)
{
}

void TButtonDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionButton *btnStyle = new QStyleOptionButton;
    //btnStyle->text = index.data().toString();
    btnStyle->text = QString("发送");
    btnStyle->rect = option.rect;            //设置按钮区域为当前item的rect
    btnStyle->state = QStyle::State_Enabled;
    // index.data(Qt::UserRole);
    btnStyle->state |= index.data(Qt::UserRole).toBool() ? QStyle::State_Sunken : QStyle::State_Raised; //设置按钮状态
    btnStyle->icon = QIcon(":/icons/icons/icons8-send-32.png");
    btnStyle->iconSize = QSize(10,10);
    QPushButton *btn = new QPushButton;
    btn->style()->drawControl(QStyle::CE_PushButton, btnStyle, painter,btn);   //将按钮绘制出来
}

bool TButtonDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    Q_UNUSED(model);
    QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
    if(option.rect.contains(mouseEvent->pos()))
    {
        //此次将会发送两次信号（按下触发和释放触发），若只需要一次信号则添加判断即可
        //判断按下：event->type() == QEvent::MouseButtonPress
        //判断释放：event->type() == QEvent::MouseButtonRelease
        if(event->type() == QEvent::MouseButtonPress)
        {
            emit clicked(index.row());
            model->setData(index,true,Qt::UserRole);

        }
        else if(event->type() == QEvent::MouseButtonRelease)
        {
            model->setData(index,false,Qt::UserRole);
        }
    }
    return true;
}


